//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.yaukie.base.util;

import com.google.common.base.CaseFormat;
import freemarker.template.TemplateExceptionHandler;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.ProgressCallback;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.GeneratedKey;
import org.mybatis.generator.config.JDBCConnectionConfiguration;
import org.mybatis.generator.config.JavaClientGeneratorConfiguration;
import org.mybatis.generator.config.JavaModelGeneratorConfiguration;
import org.mybatis.generator.config.ModelType;
import org.mybatis.generator.config.PluginConfiguration;
import org.mybatis.generator.config.SqlMapGeneratorConfiguration;
import org.mybatis.generator.config.TableConfiguration;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaukie.base.dto.BaseData;

public class GeneratorUtil {
    private static final Logger log = LoggerFactory.getLogger(GeneratorUtil.class);
    private static ThreadLocal<JDBCConnectionConfiguration> holder = new ThreadLocal();
    static final String CLASS_PATH = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    static final String ABSOLUTE_PATH;
    private static final String PROJECT_PATH;
    static final String MODULE_DIR;
    private static final String TEMPLATE_FILE_PATH = "/template";
    private static final String JAVA_PATH;
    private static final String RESOURCES_PATH;
    private static final String DATE;

    public GeneratorUtil() {
    }

    public static void generator(String jdbcUrl, String jdbcUserName, String jdbcPass, String driverClassName, String basePackage, String tableKey, boolean isAutoIncrement, String... tableNames) {
        JDBCConnectionConfiguration jdbcConnectionConfiguration = (JDBCConnectionConfiguration)holder.get();
        if (jdbcConnectionConfiguration == null) {
            jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
            jdbcConnectionConfiguration.setConnectionURL(jdbcUrl);
            jdbcConnectionConfiguration.setUserId(jdbcUserName);
            jdbcConnectionConfiguration.setPassword(jdbcPass);
            jdbcConnectionConfiguration.setDriverClass(driverClassName);
            holder.set(jdbcConnectionConfiguration);
        }

        String[] var9 = tableNames;
        int var10 = tableNames.length;

        for(int var11 = 0; var11 < var10; ++var11) {
            String tableName = var9[var11];
            generator(basePackage, tableName, (String)null, tableKey, isAutoIncrement);
        }

    }

    protected static void generator(String basePackage, String tableName, String modelName, String tableKey, boolean isAutoIncrement) {
        File file1 = new File(PROJECT_PATH + JAVA_PATH);
        File file2 = new File(PROJECT_PATH + RESOURCES_PATH);
        if (!file1.getAbsoluteFile().exists()) {
            file1.getAbsoluteFile().mkdirs();
        }

        if (!file2.getAbsoluteFile().exists()) {
            file2.getAbsoluteFile().mkdirs();
        }

        long start = System.currentTimeMillis();
        log.info("准备生成代码....");
        genController(basePackage, tableName, modelName);
        genService(basePackage, tableName, modelName);
        genModelAndMapper(basePackage, tableName, modelName, tableKey, isAutoIncrement);
        long end = System.currentTimeMillis();
        log.info("代码生成结束,共耗时{}毫秒....", end - start);
    }

    protected static void genModelAndMapper(String basePackage, String tableName, String modelName, String tableKey, boolean isAutoIncrement) {
        Context context = new Context(ModelType.FLAT);
        context.setId("Potato");
        context.setTargetRuntime("MyBatis3");
        context.addProperty("beginningDelimiter", "`");
        context.addProperty("endingDelimiter", "`");
        context.setJdbcConnectionConfiguration((JDBCConnectionConfiguration)holder.get());
        PluginConfiguration pluginConfiguration = new PluginConfiguration();
        pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.EqualsHashCodePlugin");
        pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.SerializablePlugin");
        context.addPluginConfiguration(pluginConfiguration);
        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
        javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
        javaModelGeneratorConfiguration.setTargetPackage(basePackage + ".model");
        context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);
        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
        sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH);
        sqlMapGeneratorConfiguration.setTargetPackage("mapper");
        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
        javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
        javaClientGeneratorConfiguration.setTargetPackage(basePackage + ".dao.mapper");
        javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
        TableConfiguration tableConfiguration = new TableConfiguration(context);
        tableConfiguration.setTableName(tableName);
        tableConfiguration.setDomainObjectName(modelName);
        tableConfiguration.setGeneratedKey(new GeneratedKey(tableKey, "Mysql", isAutoIncrement, (String)null));
        context.addTableConfiguration(tableConfiguration);

        ArrayList warnings;
        MyBatisGenerator generator;
        try {
            Configuration config = new Configuration();
            config.addContext(context);
            config.validate();
            boolean overwrite = true;
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            warnings = new ArrayList();
            generator = new MyBatisGenerator(config, callback, warnings);
            generator.generate((ProgressCallback)null);
        } catch (Exception var16) {
            throw new RuntimeException("生成Model和Mapper失败", var16);
        }

        if (!generator.getGeneratedJavaFiles().isEmpty() && !generator.getGeneratedXmlFiles().isEmpty()) {
            if (StringUtils.isEmpty(modelName)) {
                modelName = tableNameConvertUpperCamel(tableName);
            }

            log.info("======={}========" + modelName + ".java 生成成功");
            log.info("======={}========" + modelName + "Mapper.java 生成成功");
            log.info("======={}========" + modelName + "Mapper.xml 生成成功");
        } else {
            throw new RuntimeException("生成Model和Mapper失败：" + warnings);
        }
    }

    protected static void genService(String basePackage, String tableName, String modelName) {
        try {
            freemarker.template.Configuration cfg = getConfiguration();
            Map<String, Object> data = new HashMap();
            data.put("date", DATE);
            data.put("author", "yuenbin");
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            data.put("modelNameLowerCamel", tableNameConvertLowerCamel(tableName));
            data.put("basePackage", basePackage);
            File file = new File(PROJECT_PATH + JAVA_PATH + packageConvertPath(basePackage) + "/service/api/" + modelNameUpperCamel + "Service.java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            log.info("======{}======准备生成" + modelNameUpperCamel + "Service.java");
            cfg.getTemplate("template-service.ftl").process(data, new FileWriter(file));
            log.info(modelNameUpperCamel + "Service.java 生成成功");
            File file1 = new File(PROJECT_PATH + JAVA_PATH + packageConvertPath(basePackage) + "/service/impl/" + modelNameUpperCamel + "ServiceImpl.java");
            if (!file1.getParentFile().exists()) {
                file1.getParentFile().mkdirs();
            }

            log.info("======{}======准备生成" + modelNameUpperCamel + "ServiceImpl.java");
            cfg.getTemplate("template-serviceimpl.ftl").process(data, new FileWriter(file1));
            log.info("======{}======" + modelNameUpperCamel + "ServiceImpl.java 生成成功");
        } catch (Exception var8) {
            throw new RuntimeException("生成Service失败", var8);
        }
    }

    protected static void genController(String basePackage, String tableName, String modelName) {
        try {
            freemarker.template.Configuration cfg = getConfiguration();
            String[] split = tableName.split("_");
            String tableLastName = split[1];
            String modelLastName = firstToCapital(tableLastName);
            Map<String, Object> data = new HashMap();
            data.put("date", DATE);
            data.put("author", "yuenbin");
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
            data.put("basePackage", basePackage);
            data.put("tableLastName", tableLastName);
            data.put("modelLastName", modelLastName);
            data.put("modelName", "controller");
            File file = new File(PROJECT_PATH + JAVA_PATH + packageConvertPath(basePackage) + "/controller/" + modelNameUpperCamel + "Controller.java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            log.info("======{}======准备生成" + modelNameUpperCamel + "Controller.java");
            cfg.getTemplate("template-controller.ftl").process(data, new FileWriter(file));
            log.info("======={}======" + modelNameUpperCamel + "Controller.java 生成成功");
        } catch (Exception var10) {
            throw new RuntimeException("生成Controller失败", var10);
        }
    }

    protected static void genRequestVO(String basePackage, String tableName, String modelName) {
        genVO(basePackage, tableName, modelName, packageConvertPath(basePackage) + "/vo/request/", "RequestVO");
    }

    protected static void genResponseVO(String basePackage, String tableName, String modelName) {
        genVO(basePackage, tableName, modelName, packageConvertPath(basePackage) + "/vo/response/", "ResponseVO");
    }

    protected static void genEntityVO(String basePackage, String tableName, String modelName) {
        genVO(basePackage, tableName, modelName, packageConvertPath(basePackage) + "/vo/entity/", "EntityVO");
    }

    protected static void genVO(String basePackage, String tableName, String modelName, String packagePath, String className) {
        try {
            freemarker.template.Configuration cfg = getConfiguration();
            List<BaseData> baseDataList = DatabaseUtil.getBaseDataList(tableName);
            Map<String, Object> data = new HashMap();
            data.put("date", DATE);
            data.put("author", "yuenbin");
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
            data.put("basePackage", basePackage);
            data.put("baseDataList", baseDataList);
            File file = new File(PROJECT_PATH + JAVA_PATH + packagePath + modelNameUpperCamel + className + ".java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            log.info("======={}=======准备生成" + modelNameUpperCamel + className + ".java");
            cfg.getTemplate("template-" + className + ".ftl").process(data, new FileWriter(file));
            log.info("======={}=======" + modelNameUpperCamel + className + ".java 生成成功");
        } catch (Exception var10) {
            throw new RuntimeException(className, var10);
        }
    }

    private static freemarker.template.Configuration getConfiguration() throws IOException {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
        cfg.setClassForTemplateLoading(GeneratorUtil.class, "/template");
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        return cfg;
    }

    private static String tableNameConvertLowerCamel(String tableName) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tableName.toLowerCase());
    }

    private static String tableNameConvertUpperCamel(String tableName) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());
    }

    private static String tableNameConvertMappingPath(String tableName) {
        tableName = tableName.toLowerCase();
        return "/op/" + (tableName.contains("_") ? tableName.replaceAll("_", "") + "/" : tableName + "/");
    }

    private static String modelNameConvertMappingPath(String modelName) {
        String tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, modelName);
        return tableNameConvertMappingPath(tableName);
    }

    private static String packageConvertPath(String packageName) {
        return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
    }

    private static String firstToCapital(String str) {
        char[] chars = str.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char)(chars[0] - 32);
        }

        return new String(chars);
    }

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
    }

    static {
        ABSOLUTE_PATH = CLASS_PATH.substring(CLASS_PATH.indexOf("/") + 1);
        PROJECT_PATH = System.getProperty("user.dir");
        MODULE_DIR = ABSOLUTE_PATH.substring(PROJECT_PATH.length(), ABSOLUTE_PATH.indexOf("/target"));
        JAVA_PATH = MODULE_DIR + "/src/main/java/";
        RESOURCES_PATH = MODULE_DIR + "/src/main/resources";
        DATE = (new SimpleDateFormat("yyyy/MM/dd HH/mm/SS")).format(new Date());
    }
}
